package com.baosight.sczx.zm.cp.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.StaticBlocks;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.cp.ProducePlan;
import com.baosight.sczx.common.zm.cInterface.cp.ProducePlanJJ;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.common.zm.cInterface.cs.RoadWay;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlan;
import com.baosight.sczx.zm.cp.domain.ZMCPProducePlanJJ;
import com.baosight.sczx.zm.cp.domain.ZMCPProfessionalPlan;

/**
 * 掘进专业计划主表
 * @author wealupa
 * By.严洪浩
 */
public class ServiceZMCP12 extends ServiceEPBase {

	/**
	 * 初始进入掘进专业计划主表
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) {
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的		
		EiInfo outInfo = this.query(inInfo);
		return outInfo;
	}
	
	/**
	 * 查询掘进专业计划
	 */
	@Override
	public EiInfo query(EiInfo inInfo) {
		StaticTools.setQueryParameters(inInfo, "fdPlanType", "掘进计划", true);
		StaticTools.setQueryParameters(inInfo, "fdMiningId", UserSession.getInSessionProperty("miningCode"), true);
//		StaticTools.setQueryParameters(inInfo, "fdCreateDepartmentId", UserSession.getInSessionProperty("orgCode"), true);//所在部门ID
		
		EiInfo outInfo = super.query(inInfo, "ZMCPProfessionalPlan.query", new ZMCPProfessionalPlan());
		
		outInfo.addBlock(Department.getInstance().getMiningDepts("cmes.cp.department", "orgCode", "orgName", true, UserSession.getInSessionProperty("miningCode").toString()));	
		outInfo.addBlock(RoadWay.getMiningRoadWay("cmes.cp.roadway", true, UserSession.getInSessionProperty("miningCode").toString()));
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.mineRock", true));//煤岩类别
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.supportingType", true));//支护方式
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.roadwayUsing", true));//巷道用途
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.qualityGrade", true));//质量等级
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cs.grubProcess", true));//掘进方式
		outInfo.addBlock(StaticBlocks.getBlockData("cmes.cs.engineeringClass", new String[] { "开拓", "回采", "准备", "延伸" }, new String[] { "开拓", "回采", "准备", "延伸" }, true));// 工程类型
		outInfo.addBlock(StaticBlocks.getBlockData("cmes.cp.yesOrNo", new String[]{"是", "否"}, new String[]{"是", "否"}, false));//是否综掘巷道
		outInfo.addBlock(StaticBlocks.getBlockData("cmes.cp.zzType", new String[]{"机械"}, new String[]{"机械"}, true));//装渣方式
		outInfo.addBlock(StaticBlocks.getPlanMonth("cmes.cp.planMonth", true));
		outInfo.addBlock(StaticBlocks.getPlanStatus("cmes.cp.planStatus", true));
		
		return outInfo;
	}
	
	/**
	 * 新增掘进专业计划主表
	 */
	@SuppressWarnings("rawtypes")
	@Override	
	public EiInfo insert(EiInfo inInfo) {
		//校验是否重复
		EiInfo out = new EiInfo(); 
		ZMCPProfessionalPlan _proPlan = new ZMCPProfessionalPlan();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_proPlan.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		for (int i = 0; i < rowcount; i++) {
			_proPlan.fromMap(eiBlock.getRow(i));//获取数据
			Map<String, String>	_map = new HashMap<String, String>();
			String fdPlanType = _proPlan.getFdPlanType();
			String fdPlanYear = _proPlan.getFdPlanYear();
			String fdPlanMonth = _proPlan.getFdPlanMonth();
			String fdMiningId = UserSession.getInSessionProperty("miningCode").toString();
			
			_map.put("fdPlanType", fdPlanType);
			_map.put("fdPlanYear", fdPlanYear);
			_map.put("fdPlanMonth", fdPlanMonth);
			_map.put("fdMiningId", fdMiningId);
			List validate = dao.query("ZMCPProfessionalPlan.insertValidate", _map);
			if(validate != null && validate.size() > 0) {
				out = this.query(inInfo);
				out.setMsg(fdPlanYear + "年" + fdPlanMonth + "月的掘进专业计划已经存在！");
				return out;
			}
			else {		
				_proPlan.setFdCreatorId(UserSession.getUserId().toString());
				_proPlan.setFdCreator(UserSession.getInSessionProperty("UserCname").toString());
				_proPlan.setFdCreateDepartmentId(UserSession.getInSessionProperty("orgCode").toString());
				_proPlan.setFdCreateDepartment(UserSession.getInSessionProperty("orgName").toString());
				_proPlan.setFdMiningId(UserSession.getInSessionProperty("miningCode").toString());
				_proPlan.setFdMiningName(UserSession.getInSessionProperty("miningName").toString());
				_proPlan.setFdKeyId(TablePk.getInstance().getNextValue("T_CP_PROFESSIONALPLAN"));//主键
				
				//如果有附件上传功能的模块，需要增加以下生成docid方法。生成规则调用统一的方法。修改时不用管docid，也就是docid一旦生成不能修改。除非删除
				_proPlan.setFdDocId(StaticTools.getDocId());
				this.dao.insert("ZMCPProfessionalPlan.insert", _proPlan);
			}
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out; 
	}
	
	/**
	 * 更新掘进专业计划主表
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public EiInfo update(EiInfo inInfo) {				
		EiInfo out = new EiInfo(); 
		ZMCPProfessionalPlan _dom = new ZMCPProfessionalPlan();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		Map<String, String>	params = new HashMap<String, String>();
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
            params.put("fdProfessionalplanId", _dom.getFdKeyId());
			
			String fdPlanYear = _dom.getFdPlanYear();
			String fdPlanMonth = _dom.getFdPlanMonth();
			
//			boolean validate = ProducePlanJJ.validate(params);
//			if(validate) {
//				out = this.query(inInfo);
//				out.setMsg(fdPlanYear + "年"+ fdPlanMonth +"月掘进专业计划包含详细计划，不可修改！");
//				return out;
//			} else {
				String fdPlanType = _dom.getFdPlanType();
				String fdMiningId = UserSession.getInSessionProperty("miningCode").toString();
				
				params.put("fdPlanType", fdPlanType);
				params.put("fdPlanYear", fdPlanYear);
				params.put("fdPlanMonth", fdPlanMonth);
				params.put("fdMiningId", fdMiningId);
				List _result = dao.query("ZMCPProfessionalPlan.updateValidate", params);
				if(_result != null && _result.size() > 0) {
					out = this.query(inInfo);
					out.setMsg(fdPlanYear + "年"+ fdPlanMonth +"月的掘进专业计划已经存在！");
					return out;
				}
				else {
				      this.dao.update("ZMCPProfessionalPlan.update", _dom);
				}	
//			}
		}	
		
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;    
	}
	
	/**
	 * 删除掘进专业计划主表
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) {
		EiInfo out=new EiInfo(); 
		ZMCPProfessionalPlan _dom = new ZMCPProfessionalPlan();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		Map<String, String>	params = new HashMap<String, String>();
		for (int i = 0; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			params.put("fdProfessionalplanId", _dom.getFdKeyId());
			boolean validate = ProducePlanJJ.validate(params);
			if(validate) {
				out = this.query(inInfo);
				out.setMsg("掘进专业计划包含详细计划，不可删除！");
				return out;
			}
			else {
				this.dao.delete("ZMCPProfessionalPlan.delete", _dom);
			}
		}
		EiInfo outInfo = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return outInfo;
	}
	
	/**
	 * 掘进专业计划上报
	 * @param inInfo
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public EiInfo report(EiInfo inInfo) {
		String fdPlanYear = inInfo.getBlock("result").getCellStr(0, "fdPlanYear");
		String fdPlanMonth = inInfo.getBlock("result").getCellStr(0, "fdPlanMonth");
		
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		_map.put("fdPlanStatus", "草拟");
		
		List result = this.dao.query("ZMCPProfessionalPlan.query", _map);
		//1.0 进度完成
		if (result == null || result.isEmpty()) {
			inInfo.setStatus(-1);
			inInfo = this.query(inInfo);
			inInfo.setMsg(fdPlanYear +"年"+ fdPlanMonth +"月计划已经上报或作废，不能上报！");
			return inInfo;
		}
		
		//判断是否有明细
		Map<String, String> map = new HashMap<String, String>();
		map.put("fdProfessionalplanId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		boolean validate = ProducePlanJJ.validate(map);
		if (!validate) {
			inInfo.setStatus(-1);
			inInfo = this.query(inInfo);
			inInfo.setMsg("上报的"+ fdPlanYear +"年"+ fdPlanMonth +"月计划中有的没有明细，请添加明细后上报！");
			return inInfo;
		}
		
		//2.0进度完成
		String fdProduceplanId = ProducePlan.checkCanReport(inInfo);
		//3.0进度完成
		
		if (fdProduceplanId == null) {
			//生产计划已经生效
			inInfo.getBlock("result").setCell(0, "fdPlanStatus", "作废");
			this.update(inInfo, "ZMCPProfessionalPlan.updatePlanStatus");
		}
		else {
			//生产计划不存在主表 或 主表为草拟
			inInfo.getBlock("result").setCell(0, "fdPulisherId", UserSession.getUserId());
			inInfo.getBlock("result").setCell(0, "fdPulisher", UserSession.getInSessionProperty("UserCname"));
			inInfo.getBlock("result").setCell(0, "fdPlanStatus", "上报");
			this.update(inInfo, "ZMCPProfessionalPlan.updatePlanStatus");
			//4.0进度完成
			
			//5.0进度完成
			ProducePlanJJ.cloneJJ(fdProduceplanId, inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
			
			//重新计算生产计划采煤方向的数据
			//6.0进度完成
			List<String> _list = new ArrayList<String>();
			_list.add(inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
			ProducePlan.updateByJJ(fdProduceplanId, _list, 1);
		}
		
		EiInfo outInfo = this.query(inInfo);
		if(fdProduceplanId == null) {
			outInfo.setMsg(fdPlanYear +"年"+ fdPlanMonth +"月的生产计划已经发布，上报无效，原纪录作废！");
		}
		else {
			outInfo.setMsg(fdPlanYear +"年"+ fdPlanMonth +"月的掘进计划上报成功！");
		}
		return outInfo;
	}
	
	/**
	 * 专业计划撤回上报
	 * @param inInfo
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public EiInfo goback(EiInfo inInfo) {
		//1.0判断当月生产计划是否已经生效
		String fdPlanYear = inInfo.getBlock("result").getCellStr(0, "fdPlanYear");
		String fdPlanMonth = inInfo.getBlock("result").getCellStr(0, "fdPlanMonth");
		String fdMiningId = inInfo.getBlock("result").getCellStr(0, "fdMiningId");

		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdPlanYear", fdPlanYear);
		_map.put("fdPlanMonth", fdPlanMonth);
		_map.put("fdMiningId", fdMiningId);
		
		List result = ProducePlan.goback(_map);
		boolean canBack = true;
		
		String fdProduceplanId = null;
		
		if(result != null && result.size() > 0) {
			for(int i = 0; i < result.size(); i++) {
				ZMCPProducePlan plan = (ZMCPProducePlan)result.get(i);
				if(plan.getFdPlanStatus().equals("生效")) {
					canBack = false;
				}
				if(plan.getFdPlanStatus().equals("草拟")) {
					fdProduceplanId = plan.getFdKeyId();
				}
			}
			
			if(!canBack) {
				inInfo.setStatus(-1);
				inInfo = this.query(inInfo);
				inInfo.setMsg(fdPlanYear +"年"+ fdPlanMonth +"月的生产计划已经整体发布，不能撤回！");
				return inInfo;
			}
			
			//2.0删除生产计划中，从表的数据
			String fdProfessionalplanId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");
			ProducePlanJJ.goback(fdProfessionalplanId);
			
			//3.0从新计算生产计划主表的数据
			if(fdProduceplanId != null) {
				List<String> _list = new ArrayList<String>();
				_list.add(inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
				ProducePlan.updateByJJ(fdProduceplanId, _list, 2);
			}
		}
		
		//4.0更改专业计划的状态为草拟
		Map<String, String> params = new HashMap<String, String>();
		params.put("fdKeyId", inInfo.getBlock("result").getCellStr(0, "fdKeyId"));
		params.put("fdPlanStatus", "上报");
		
		int rowcount = dao.update("ZMCPProfessionalPlan.goback", params);
		
		EiInfo out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;
	}
	
	/**
	 * 复制
	 */
	@SuppressWarnings("unchecked")
	public EiInfo copy(EiInfo inInfo) {
		// 查找表中的最近 年份+月份
		String fdMiningId = UserSession.getInSessionProperty("miningCode")
				.toString();
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdMiningId", fdMiningId);
		_map.put("fdPlanType", "掘进计划");
		List<ZMCPProfessionalPlan> list = dao.query(
				"ZMCPProfessionalPlan.query", _map);
		ZMCPProfessionalPlan zm = (ZMCPProfessionalPlan) list.get(0);

		String year = zm.getFdPlanYear() == null ? StaticTools.getYear() : zm
				.getFdPlanYear().trim();
		String month = zm.getFdPlanMonth() == null ? StaticTools.getMonth()
				: zm.getFdPlanMonth().trim();

		String oldKeyId = inInfo.getBlock("result").getCellStr(0, "fdKeyId");

		// 处理年份和月份
		if (Integer.parseInt(month) >= 12) {
			month = "01";
			year = String.valueOf(Integer.parseInt(year) + 1);
		} else {
			month = String.valueOf(Integer.parseInt(month) + 1);
			if (month.length() == 1) {
				month = "0" + month;
			}
		}

		// 添加主表信息给复制行信息 -- 插入
		String fdProfessionalplanId = TablePk.getInstance().getNextValue(
				"T_CP_PROFESSIONALPLAN");
		inInfo.getBlock("result").setCell(0, "fdPlanYear", year);
		inInfo.getBlock("result").setCell(0, "fdPlanMonth", month);
		inInfo.getBlock("result").setCell(0, "fdKeyId", fdProfessionalplanId);
		inInfo.getBlock("result").setCell(0, "fdPlanStatus", "草拟");
		inInfo.getBlock("result").setCell(0, "fdTitle",
				year + "年" + month + "月的掘进计划");

		inInfo.getBlock("result").setCell(0, "fdCreateDate",StaticTools.getDate());
		inInfo.getBlock("result").setCell(0, "fdCreatorId",UserSession.getUserId().toString());
		inInfo.getBlock("result").setCell(0, "fdCreator",UserSession.getInSessionProperty("UserCname").toString());
		inInfo.getBlock("result").setCell(0, "fdCreateDepartmentId",UserSession.getInSessionProperty("orgCode").toString());
		inInfo.getBlock("result").setCell(0, "fdCreateDepartment",UserSession.getInSessionProperty("orgName").toString());
	//不设置fdBhcsl、fdZhcsl报错
		inInfo.getBlock("result").setCell(0, "fdBhcsl", null);
		inInfo.getBlock("result").setCell(0, "fdZhcsl", null);
		inInfo.getBlock("result").setCell(0, "fdPulisherId", null);
		inInfo.getBlock("result").setCell(0, "fdPulisher", null);

		super.insert(inInfo, "ZMCPProfessionalPlan.insert", "result");

		// 获取选取记录的ID
		Map<String, String> map = new HashMap<String, String>();
		map.put("fdProfessionalplanId", oldKeyId);
		map.put("isProfessionalplan", "任意数值");

		List<ZMCPProducePlanJJ> CMlist = dao.query("ZMCPProducePlanJJ.query",
				map);
		for (int i = 0; i < CMlist.size(); i++) {
			ZMCPProducePlanJJ zmcp = CMlist.get(i);
			zmcp.setFdKeyId(TablePk.getInstance().getNextValue(
					"T_CP_PRODUCEPLAN_JJ"));
			zmcp.setFdProfessionalplanId(fdProfessionalplanId);
			dao.insert("ZMCPProducePlanJJ.insert", zmcp.toMap());
		}

		EiInfo out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作 记录成功");
		return out;
	}
}
